from django.shortcuts import render
from goods.models import Goods
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.views import View
from utils.LoginRequremixIn import LoginRequireMixIn
# Create your views here.


def post_relif(request, count=''):
    user = request.user
    if not user.is_authenticated:
        return JsonResponse({'res': 0, 'errmsg': '请先登录'})
    goods_id = request.POST.get('goods_id')

    if not all([goods_id]):
        return JsonResponse({'res': 1, 'errmsg': '数据不完整'})

    try:
        goods = Goods.objects.get(pk=goods_id)
    except goods.DoesNotExist:
        return JsonResponse({'res': 2, 'errmsg': '商品不存在'})

    # 查看redis是否存在cart_id
    conn = get_redis_connection('default')
    cart_key = 'cart_%d' % user.id
    # hget如果没有goods_id返回None
    cart_count = conn.hget(cart_key, goods_id)
    if not cart_count:
        cart_count = 1
    elif count == '':
        cart_count = int(cart_count) + 1
    else:
        cart_count = int(count)

    if cart_count > goods.stock:
        return JsonResponse({'res': 3, 'errmsg': '库存不足'})

    conn.hset(cart_key, goods_id, cart_count)
    total_count = conn.hlen(cart_key)
    return JsonResponse({'res': 4, 'errmsg': '添加成功', 'total_count': total_count})


class CartAdd(View):
    def post(self, request):
        return post_relif(request)


class Cart(LoginRequireMixIn, View):
    def get(self, request):
        user = request.user
        if not user.is_authenticated:
            return render(request, 'cart.html')
        conn = get_redis_connection('default')
        cart_key = 'cart_%d'%user.id
        cart_count = conn.hlen(cart_key)
        cart_dict = conn.hgetall(cart_key)
        goods_list = []
        total_count = 0
        total_price = 0
        for goods_id, count in cart_dict.items():
            goods = Goods.objects.get(pk=goods_id)
            goods.count = int(count)
            goods.amount = goods.price*int(count)
            goods_list.append(goods)
            total_count += int(count)
            total_price += goods.amount

        context = {'total_price': total_price, 'cart_count': cart_count, 'total_count': total_count, 'goods_list': goods_list}

        return render(request, 'cart.html', context)


class CartUpdate(View):
   def post(self, request):
       count = request.POST.get('count')
       return post_relif(request, count)


class CartDelete(View):
    def post(self, request):
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': '用户未登陆'})
        goods_id = request.POST.get('goods_id')

        if not all([goods_id]):
            return JsonResponse({"res": 1, 'errmsg': '数据不完整'})
        try:
            goods = Goods.objects.get(pk=goods_id)
        except:
            return JsonResponse({"res": 2, 'errmsg': '商品不存在'})
        conn = get_redis_connection('default')
        cart_id = "cart_%d" %user.id
        conn.hdel(cart_id, goods_id)
        return JsonResponse({'res': 3, 'errmsg': 'ok'})

